from typing import List

from fastapi import APIRouter, Depends
import json
from sqlalchemy import select, desc, func, distinct
from sqlalchemy.ext.asyncio import AsyncSession
from apis.deps import get_db
from schemas import CaseInterfaceListUpdate, CaseInterfaceListCreate, CaseInterfaceListOut as CaseInterfaceList, Result, \
    ResultPlus
from crud import caseList, caseInterfaceList
from utils import resp_200, IdNotExist
from models import CaseInterfaceList as CaseInterfaceListModel

router = APIRouter()


@router.post("/createCaseInterfaceList", response_model=Result, summary="新增用例接口列表")
async def createCaseInterfaceList(caseInterfaceList_in: CaseInterfaceListCreate, db: AsyncSession = Depends(get_db)):
    await caseInterfaceList.create(db=db, obj_in=caseInterfaceList_in)
    return resp_200(msg=f"成功添加接口用例列表")


@router.get("/getCaseInterfaceList", response_model=ResultPlus[CaseInterfaceList], summary="查询用例接口列表")
async def getCaseInterfaceList(pageIndex: int = 1, pageSize: int = 10, queryName: str = '', caseListId: int = 0,
                               db: AsyncSession = Depends(get_db)):
    sql1 = select(CaseInterfaceListModel).offset((pageIndex - 1) * pageSize).limit(pageSize).where(
        CaseInterfaceListModel.name.like(f'%{queryName}'), CaseInterfaceListModel.caseListId == caseListId).order_by(
        desc(CaseInterfaceListModel.id))
    result1 = await db.execute(sql1)
    caseInterfaceList = result1.scalars().all()
    sql2 = select(func.count(distinct(CaseInterfaceListModel.id))).where(CaseInterfaceListModel.caseListId == caseListId)
    count = await db.scalar(sql2)
    return resp_200(data={"count": count, "list": caseInterfaceList}, msg=f"查询成功")


@router.put("/updateCaseInterfaceList", response_model=Result, summary="通过id更新用例接口列表信息")
async def updateCaseInterfaceList(id: int, caseInterfaceList_in: CaseInterfaceListUpdate,
                                  db: AsyncSession = Depends(get_db)):
    row = await caseInterfaceList.update(db, id, obj_in=caseInterfaceList_in)
    return resp_200(msg="成功更新用例列表信息")


@router.delete('/deleteCaseInterfaceList', response_model=Result, summary="通过id删除用例接口列表信息")
async def deleteCaseInterfaceList(id: int, db: AsyncSession = Depends(get_db)):
    row = await caseInterfaceList.remove(db, id)
    return resp_200(msg="成功删除用例接口列表信息")


@router.put("/updateStatus", response_model=Result, summary="通过id更新用例接口列表状态")
async def updateStatus(id: int, db: AsyncSession = Depends(get_db)):
    caseInterfaceList = await db.get(CaseInterfaceListModel, id)
    caseInterfaceList.status = not caseInterfaceList.status
    await db.commit()
    return resp_200(msg="用例接口列表状态更新成功")
